package com.cyf.xjtechdemo

import android.annotation.SuppressLint
import android.graphics.*
import android.os.Bundle
import android.view.MotionEvent
import android.view.SurfaceView
import android.view.View
import android.widget.AdapterView
import androidx.appcompat.app.AppCompatActivity
import com.cyf.image_conversion.ImageConversion
import com.cyf.xjtech_android.XJTechSDK
import kotlinx.android.synthetic.main.activity_main.*
import org.jetbrains.anko.doAsync


class MainActivity : AppCompatActivity() {

    private val paint by lazy {
        Paint(Color.RED)
    }

    private val paintGreen by lazy {
        Paint(Color.GREEN)
    }

    private val pointTemp by lazy {
        PointF(200f, 200f)
    }
    private var flag = false
    private var setHidden = false
    //private val sample = listOf(0, 1, 2, 3, 4, 5, 15, 16, 17, 18, 19, 30, 31, 32, 33, 45, 46)

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        open.setOnClickListener {
            if (open.text == "打开相机") {
                if (openCamera()) {
                    open.text = "关闭相机"
//                    for (i in sample.indices) {
//                        hiddenPos.add(sample[i])
//                    }
//                    XJTechSDK.setHiddenArea(15, 10, hiddenPos)
                }
            } else {
                closeCamera()
                open.text = "打开相机"
            }
        }

        openBDConfig.setOnClickListener {
            if (openBDConfig.text == "打开黑体矫正") {
                if (openBdCorrect()) {
                    openBDConfig.text = "关闭黑体矫正"
                }
            } else {
                closeBdCorrect()
                openBDConfig.text = "打开黑体矫正"
            }
        }

        palette.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
            override fun onItemSelected(p0: AdapterView<*>?, p1: View?, p2: Int, p3: Long) {
                XJTechSDK.setPalette(p2)
            }

            override fun onNothingSelected(p0: AdapterView<*>?) {
                XJTechSDK.setPalette(0)
            }
        }

        shutter.setOnClickListener {
            XJTechSDK.shutterCorrect()
        }

        armpit.setOnClickListener {
            if (armpit.text == "打开腋下温度") {
                XJTechSDK.setArmpitEnable(true)
                armpit.text = "关闭腋下温度"
            } else {
                XJTechSDK.setArmpitEnable(false)
                armpit.text = "打开腋下温度"
            }
        }

        hideArea.setOnClickListener {
            if (hideArea.text == "屏蔽区域") {
                setHidden = true
                hideArea.text = "完成"
            } else {
                setHidden = false
                hideArea.text = "屏蔽区域"
                XJTechSDK.setHiddenArea(HIDDEN_W, HIDDEN_H, hiddenPos)
            }
        }

        surfaceView.setOnTouchListener(onTouchListener)
        paint.color = Color.RED
        paint.textSize = 20f
        draw()
    }

    @SuppressLint("ClickableViewAccessibility")
    private val onTouchListener = View.OnTouchListener { p0, event ->
        if (setHidden) {
            val hiddenRectW = surfaceView.width.toFloat() / HIDDEN_W
            val hiddenRectH = surfaceView.height.toFloat() / HIDDEN_H
            when (event?.action) {
                MotionEvent.ACTION_DOWN -> {
                    val w = (event.x / hiddenRectW).toInt()
                    val h = (event.y / hiddenRectH).toInt()
                    val ret = h * HIDDEN_W + w
                    if (!tempsPos.contains(ret)) {
                        tempsPos.add(ret)
                    }
                }
                MotionEvent.ACTION_MOVE -> {
                    val w = (event.x / hiddenRectW).toInt()
                    val h = (event.y / hiddenRectH).toInt()
                    val ret = h * HIDDEN_W + w
                    if (!tempsPos.contains(ret)) {
                        tempsPos.add(ret)
                    }
                }
                MotionEvent.ACTION_UP -> {
                    for (i in 0 until tempsPos.size) {
                        if (hiddenPos.contains(tempsPos[i])) {
                            hiddenPos.remove(tempsPos[i])
                        } else {
                            hiddenPos.add(tempsPos[i])
                        }
                    }
                    tempsPos.clear()
                }
            }
        } else {
            val off = 200
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    pointTemp.set(event.x - off, event.y - off)
                }
                MotionEvent.ACTION_MOVE -> {
                    pointTemp.set(event.x - off, event.y - off)
                }
                MotionEvent.ACTION_UP -> {
                    pointTemp.set(event.x - off, event.y - off)
                }
            }
        }

        true
    }

    override fun onDestroy() {
        flag = false
        super.onDestroy()
    }

    private fun draw() {
        flag = true
        doAsync {
            Thread.sleep(500)
            while (flag) {
                val temprData = XJTechSDK.pullData() ?: continue
                val ccIR = surfaceView.holder.lockCanvas() ?: continue
                ccIR.drawColor(Color.BLACK)
                val bitmap = ImageConversion.RGB2BGRA_BITMAP(
                    temprData.bmp,
                    temprData.width,
                    temprData.height
                )
                ccIR.drawBitmap(bitmap, bitmap.getRect(), surfaceView.getRect(), paint)
                if (setHidden) {
                    ccIR.showGridLayout()
                } else {
                    val maxPoint =
                        (PointF(temprData.maxX.toFloat(), temprData.maxY.toFloat())).image2View()
                    ccIR.showPoint(
                        maxPoint.x,
                        maxPoint.y,
                        temprData.max
                    )
//                    val minPoint =
//                        (PointF(temprData.minX.toFloat(), temprData.minY.toFloat())).image2View()
//                    ccIR.showPoint(
//                        minPoint.x,
//                        minPoint.y,
//                        temprData.min
//                    )
                    val imagePoint = pointTemp.view2Image()
                    val temper =
                        XJTechSDK.getTemprByPoint(imagePoint.x.toInt(), imagePoint.y.toInt())
                    ccIR.showPoint(pointTemp.x, pointTemp.y, temper)
                }
                surfaceView.holder.unlockCanvasAndPost(ccIR)
                Thread.sleep(80)
            }
        }
    }

    private val HIDDEN_W = 15
    private val HIDDEN_H = 10
    private val hiddenPos = arrayListOf<Int>()
    private val tempsPos = arrayListOf<Int>()

    private fun Canvas.showGridLayout() {
        val hiddenRectW = surfaceView.width.toFloat() / HIDDEN_W
        val hiddenRectH = surfaceView.height.toFloat() / HIDDEN_H
        paintGreen.color = Color.GREEN
        paintGreen.style = Paint.Style.FILL
        //绘制网格
        for (i in 1 until HIDDEN_W) {
            drawLine(hiddenRectW * i, 0f, hiddenRectW * i, surfaceView.height.toFloat(), paintGreen)
        }
        for (i in 1 until HIDDEN_H) {
            drawLine(0f, hiddenRectH * i, surfaceView.width.toFloat(), hiddenRectH * i, paintGreen)
        }
        for (i in 0 until hiddenPos.size) {
            val w = hiddenPos[i] % HIDDEN_W
            val h = hiddenPos[i] / HIDDEN_W
            if (!tempsPos.contains(hiddenPos[i])) {
                drawRect(
                    w * hiddenRectW,
                    h * hiddenRectH,
                    (w + 1) * hiddenRectW,
                    (h + 1) * hiddenRectH,
                    paintGreen
                )
            }
        }
        for (i in 0 until tempsPos.size) {
            val w = tempsPos[i] % HIDDEN_W
            val h = tempsPos[i] / HIDDEN_W
            if (!hiddenPos.contains(tempsPos[i])) {
                drawRect(
                    w * hiddenRectW,
                    h * hiddenRectH,
                    (w + 1) * hiddenRectW,
                    (h + 1) * hiddenRectH,
                    paintGreen
                )
            }
        }
    }

    /**
     * 显示选择温度
     */
    private fun Canvas.showPoint(x: Float, y: Float, temper: Float) {
        drawCross(x, y)
        drawText(
            "%.2f℃".format(temper),
            x - 40,
            y + 20,
            paint
        )
        drawText(
            "x:${x}  y:${y}",
            x - 40,
            y + 40,
            paint
        )
    }

    private fun Canvas.drawCross(x: Float, y: Float) {
        drawLine(x - 15, y, x - 5, y, paint)
        drawLine(x + 5, y, x + 15, y, paint)
        drawLine(x, y - 15, x, y - 5, paint)
        drawLine(x, y + 5, x, y + 15, paint)
    }

    /**
     * 打开相机
     */
    private fun openCamera(): Boolean {
        return XJTechSDK.openCamera(ipAddr.text.toString())
    }

    /**
     * 关闭相机
     */
    private fun closeCamera() {
        doAsync {
            XJTechSDK.closeCamera()
        }
    }

    /**
     * 打开黑体矫正
     */
    private fun openBdCorrect(): Boolean {
        return XJTechSDK.setBdCorrect(true)
    }

    /**
     * 关闭黑体矫正
     */
    private fun closeBdCorrect() {
        XJTechSDK.setBdCorrect(false)
    }

    private fun Bitmap.getRect(): Rect {
        return Rect(0, 0, this.width, this.height)
    }

    private fun SurfaceView.getRect(): Rect {
        return Rect(0, 0, this.width, this.height)
    }

    private fun PointF.view2Image(): PointF {
        return XJTechSDK.transformByRect(
            this,
            surfaceView.getRect(),
            Rect(0, 0, XJTechSDK.imageWidth, XJTechSDK.imageHeight)
        )
    }

    private fun PointF.image2View(): PointF {
        return XJTechSDK.transformByRect(
            this,
            Rect(0, 0, XJTechSDK.imageWidth, XJTechSDK.imageHeight),
            surfaceView.getRect()
        )
    }


}